const { Sequelize } = require('sequelize');
const config = require('../config/database');

const env = process.env.NODE_ENV || 'development';
const dbConfig = config[env];

// 创建Sequelize实例
const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    timezone: dbConfig.timezone,
    dialectOptions: dbConfig.dialectOptions,
    pool: dbConfig.pool,
    define: dbConfig.define,
    logging: dbConfig.logging
  }
);

// 数据库模型对象
const db = {};

// 引入所有模型
db.User = require('./User')(sequelize, Sequelize.DataTypes);
db.Category = require('./Category')(sequelize, Sequelize.DataTypes);
db.Tag = require('./Tag')(sequelize, Sequelize.DataTypes);
db.Diary = require('./Diary')(sequelize, Sequelize.DataTypes);
db.DiaryTag = require('./DiaryTag')(sequelize, Sequelize.DataTypes);
db.Image = require('./Image')(sequelize, Sequelize.DataTypes);
db.Admin = require('./Admin')(sequelize, Sequelize.DataTypes);

// 设置模型关联关系
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

// 数据库连接测试
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
};

// 数据库同步
const syncDatabase = async (force = false) => {
  try {
    if (env === 'development') {
      await sequelize.sync({ force, alter: true });
      console.log('数据库同步成功');
    } else {
      await sequelize.sync();
      console.log('数据库同步成功');
    }
  } catch (error) {
    console.error('数据库同步失败:', error);
  }
};

db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.testConnection = testConnection;
db.syncDatabase = syncDatabase;

module.exports = db; 